
import router from '@/router';
import store from '@/store';
import { MessageBox, Message } from 'element-ui';
import getPageTitle from '@/utils/get-page-title';
import { getQueryObject } from './utils/utils';
// import { Message } from 'element-ui';
import { getToken, setToken, removeToken, getDynamicSiteId } from '@/utils/auth'; // getToken from cookie
const whiteList = ['/login', '/register', '/forget-password'];// no redirect whitelist

/* if (process.env.NODE_ENV === 'production') {
    const hm = document.createElement('script');
    hm.src = '';

    const s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(hm, s);
} */

router.beforeEach(async (to, from, next) => {
    document.title = getPageTitle(to.meta.title);
    if (getToken()) { // determine if there has token
        /* has token */
        if (to.path === '/login') {
            next({ path: '/' });
        } else {
            const hasRoles = store.getters.roles && store.getters.roles.length > 0;
            const siteList = store.getters.siteList;
            if (hasRoles) {
                const siteObj = getDynamicSiteId(siteList, to.query.siteName);
                if (to.query.siteName) {
                    console.log(siteObj && siteObj.id);
                    store.commit('SET_SITE_ID', ((siteObj && siteObj.id) || store.getters.siteId));
                    if (!siteObj) {
                        Message.error('站点不存在, 请检查站点名称');
                    }
                    next();
                    return;
                };
                if (from.query.siteName) {
                    let toQuery = JSON.parse(JSON.stringify(to.query));
                    toQuery.siteName = from.query.siteName;
                    console.log(siteObj && siteObj.id);
                    store.commit('SET_SITE_ID', siteObj && siteObj.id);
                    next({
                        path: to.path,
                        query: toQuery
                    });
                } else {
                    next();
                }
            } else {
                try {
                    // get user info
                    // note: roles must be a object array! such as: ['admin'] or ,['developer','theme-editor']
                    const siteObj = getDynamicSiteId(siteList, to.query.siteName);
                    await store.dispatch('GetInfo');
                    const data = await store.dispatch('GetMenus', to.query.siteName ? ((siteObj && siteObj.id) || store.getters.siteId) : store.getters.siteId);
                    const accessRoutes = await store.dispatch('GenerateRoutes', { menus: data });
                    router.addRoutes(accessRoutes);
                    // if (window._hmt) {
                    //     window._hmt.push(['_trackPageview', '/#' + to.fullPath]);
                    // }
                    next({ ...to, replace: true });
                } catch (error) {
                    // remove token and go to login page to re-login
                    await store.dispatch('ResetToken');
                    next('/login');
                    // Message.error(error || 'Has Error');
                    // next(`/login?redirect=${to.path}`);
                }
            }
        }
    } else {
        /* has no token */
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
            next();
        } else {
            next('/login');
            // next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
        }
    }
});

router.afterEach(() => {
});
